//
//  TestViewController.m
//  GentlemanAnime
//
//  Created by dlios on 15-7-4.
//  Copyright (c) 2015年 lanou3g.com 蓝欧科技. All rights reserved.
//

#import "DownloadViewController.h"
#import "AppDelegate.h"
#import "UIImageView+WebCache.h"
#import "DownloadSingletonTool.h"
#import "AnimeDetallsViewController.h"
#import "NewsDetailViewController.h"
#import "ImageDetailViewController.h"

#import "DownloadAnimeTableViewCell.h"
#import "DetailsInfoModel.h"

#import "ImageTableViewCell.h"
#import "ImageTableViewModel.h"

#import "NewsTableViewCell.h"
#import "NewsTableViewModel.h"

#import "homeAnimeViewController.h"
#import "homeNewsViewController.h"
#import "homeImageViewController.h"

#import "AppDelegate.h"
#import "LeftCollectionViewCell.h"

#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

typedef NS_ENUM(NSInteger, rightButtonState) {
    isOn = 1,
    isChanging,
    isOff
};

@interface DownloadViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property(nonatomic, assign)rightButtonState rightButtonState;
@property(nonatomic, retain)UIView *backView;
@property(nonatomic, retain)UIScrollView *leftScrollView;
@property(nonatomic, retain)UIImageView *leftSegBackView;
@property(nonatomic, retain)UISegmentedControl *leftSeg;
@property(nonatomic, retain)UITableView *leftTableView;
@property(nonatomic, retain)UILabel *titleLabel;
@property(nonatomic, assign)CGFloat oldPoint;
@property(nonatomic, assign)BOOL isScrolling;

@property(nonatomic, retain)NSMutableArray *animeArr;
@property(nonatomic, retain)NSMutableArray *newsArr;
@property(nonatomic, retain)NSMutableArray *imageArr;

@end

@implementation DownloadViewController
- (void)dealloc {
    [_titleLabel release];
    [_backView release];
    [_leftScrollView release];
    [_leftSegBackView release];
    [_leftSeg release];
    [_leftTableView release];
    [super dealloc];
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.rightButtonState = isOff;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tabBarController.tabBar.hidden = YES;
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    if ([DownloadSingleton shareDownloadSingleton].leftState == collectAnimes) {
        self.titleLabel.text = @"漫画收藏";
    } else if ([DownloadSingleton shareDownloadSingleton].leftState == collectNews) {
        self.titleLabel.text = @"漫资讯收藏";
    } else {
        self.titleLabel.text = @"漫图收藏";
    }
    self.navigationItem.titleView = self.titleLabel;
    [_titleLabel release];

    // 返回按钮
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 60, 30);
    [backButton setTitle:@"返回" forState:UIControlStateNormal];
    backButton.imageEdgeInsets = UIEdgeInsetsMake(5, 0, 5, 40);
    [backButton setImage:[UIImage imageNamed:@"单箭头"] forState:UIControlStateNormal];
    backButton.titleLabel.font = [UIFont systemFontOfSize:16];
    backButton.titleEdgeInsets = UIEdgeInsetsMake(0, - 20, 0, 0);
    backButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    // 右边分类按钮
    UIButton *fenleiButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [fenleiButton setImage:[UIImage imageNamed:@"iconfont-fenlei"] forState:UIControlStateNormal];
    fenleiButton.frame = CGRectMake(0, 0, 40, 40);
    fenleiButton.imageEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
    fenleiButton.contentEdgeInsets = UIEdgeInsetsMake(5, 20, 5, -10);
    [fenleiButton addTarget:self action:@selector(fenleiClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:fenleiButton] autorelease];
    
    // 反归档
    [self fanguidang];
    // 绘制TableView
    [self createTableView];
    // 绘制控制器
    [self createStyleSeg];
}

#pragma mark 反归档
- (void)fanguidang {
    NSArray *animeSandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *animeSandBoxPath = animeSandBox[0];
    NSString *collctAnimePath = [animeSandBoxPath stringByAppendingPathComponent:@"anime.plist"];
    self.animeArr = [NSKeyedUnarchiver unarchiveObjectWithFile:collctAnimePath];
    
    NSArray *newsSandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *newsSandBoxPath = newsSandBox[0];
    NSString *collctNewsPath = [newsSandBoxPath stringByAppendingPathComponent:@"news.plist"];
    self.newsArr = [NSKeyedUnarchiver unarchiveObjectWithFile:collctNewsPath];
    
    NSArray *imageSandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *imageSandBoxPath = imageSandBox[0];
    NSString *collectImagePath = [imageSandBoxPath stringByAppendingPathComponent:@"image.plist"];
    self.imageArr = [NSKeyedUnarchiver unarchiveObjectWithFile:collectImagePath];

}

#pragma mark 绘制控制器
- (void)createStyleSeg {
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 0)];
    self.backView.clipsToBounds = YES;
    [self.view addSubview:self.backView];
    self.backView.backgroundColor = [UIColor colorWithRed:0.299 green:0.714 blue:0.945 alpha:0.900];
    [_backView release];
    
    // 左边的ScrollView
    self.leftScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 40)];
    [self.backView addSubview:self.leftScrollView];
    [_leftScrollView release];
    self.leftScrollView.contentSize = CGSizeMake(WIDTH / 3 * 5, 0);
    self.leftScrollView.scrollEnabled = YES;
    self.leftScrollView.contentOffset = CGPointMake(WIDTH * 2 / 3, 0);
    
    // 左边的背景图
    self.leftSegBackView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 80, 35)];
    self.leftSegBackView.center = CGPointMake(WIDTH * 5 / 6,self.leftScrollView.frame.size.height / 2);
    [self.leftScrollView addSubview:self.leftSegBackView];
    self.leftSegBackView.image = [UIImage imageNamed:@"recommendSelectBar"];
    [_leftSegBackView release];
    
    // 左边的控制器
    self.leftSeg = [[UISegmentedControl alloc] initWithItems:@[@"漫画",@"漫资讯",@"漫图"]];
    self.leftSeg.frame = CGRectMake(0, 0, WIDTH, 40);
    self.leftSeg.tintColor = [UIColor clearColor];
    self.leftSeg.tag = 1001;
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15],NSFontAttributeName,  [UIColor colorWithRed:0.135 green:0.169 blue:0.571 alpha:1.000], NSForegroundColorAttributeName,nil];
    [self.leftSeg setTitleTextAttributes:dic forState:UIControlStateNormal];
    NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:17],NSFontAttributeName, [UIColor whiteColor], NSForegroundColorAttributeName,nil];
    [self.leftSeg setTitleTextAttributes:dic1 forState:UIControlStateSelected];
    [self.leftSeg addTarget:self action:@selector(segClick:) forControlEvents:UIControlEventValueChanged];
    [self.backView addSubview:self.leftSeg];
    
    if ([DownloadSingleton shareDownloadSingleton].leftState == collectAnimes) {
        self.leftSeg.selectedSegmentIndex = 0;
        self.leftScrollView.contentOffset = CGPointMake(WIDTH * 2 / 3, 0);
    } else if ([DownloadSingleton shareDownloadSingleton].leftState == collectNews) {
        self.leftSeg.selectedSegmentIndex = 1;
        self.leftScrollView.contentOffset = CGPointMake(WIDTH * 1 / 3, 0);
    } else if ([DownloadSingleton shareDownloadSingleton].leftState == collectImages){
        self.leftSeg.selectedSegmentIndex = 2;
        self.leftScrollView.contentOffset = CGPointMake(0, 0);
    }
    [_leftSeg release];
}

#pragma mark 绘制TableView
- (void)createTableView {
    // 左tableView
    self.leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.leftTableView];
    self.leftTableView.dataSource = self;
    self.leftTableView.delegate = self;
    self.leftTableView.tag = 1000;
    [_leftTableView release];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.oldPoint = scrollView.contentOffset.y;
    self.isScrolling = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.isScrolling == YES) {
        if (self.rightButtonState == isOn) {
            if (self.oldPoint - scrollView.contentOffset.y < -50) {
                self.rightButtonState = isChanging;
                [UIView animateWithDuration:0.3 animations:^{
                    self.backView.frame = CGRectMake(0, 0, WIDTH * 2, 0);
                } completion:^(BOOL finished) {
                    self.rightButtonState = isOff;
                    self.isScrolling = NO;
                }];
            }
        }
    }
}

#pragma mark tableView的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([DownloadSingleton shareDownloadSingleton].leftState == collectAnimes) {
        return self.animeArr.count;
    } else if ([DownloadSingleton shareDownloadSingleton].leftState == collectNews) {
        return self.newsArr.count;
    } else {
        return self.imageArr.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([DownloadSingleton shareDownloadSingleton].leftState == collectAnimes) {
        NSString *animeReuse = @"animeReuse";
        DownloadAnimeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:animeReuse];
        if (cell == nil) {
            cell = [[[DownloadAnimeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:animeReuse] autorelease];
        }
        DetailsInfoModel *detailsInfoModel = self.animeArr[indexPath.row];
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:detailsInfoModel.cover] placeholderImage:[UIImage imageNamed:@"漫画占位图"]];
        cell.nameLabel.text = detailsInfoModel.last_update_chapter_name;
        cell.titleLabel.text = detailsInfoModel.title;
        cell.authorLabel.text = detailsInfoModel.authors;
        cell.zoneLabel.text = detailsInfoModel.zone;
        return cell;
    } else if ([DownloadSingleton shareDownloadSingleton].leftState == collectNews) {
        NSString *newsReuse = @"newsReuse";
        NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:newsReuse];
        if (cell == nil) {
            cell = [[[NewsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:newsReuse] autorelease];
        }
        NewsTableViewModel *newsTableViewModel = self.newsArr[indexPath.row];
        [cell.AnimeImageView sd_setImageWithURL:[NSURL URLWithString:newsTableViewModel.image] placeholderImage:[UIImage imageNamed:@"新闻占位图"]];
        cell.TitleLabel.text = newsTableViewModel.title;
        cell.TimeLabel.text = newsTableViewModel.time;
        cell.BrowseLabel.text = newsTableViewModel.browse;
        cell.ReleaseLabel.text = newsTableViewModel.release;
        cell.DescribeLabel.text = newsTableViewModel.describe;
        return cell;
    } else {
        NSString *imageReuse = @"imageReuse";
        ImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:imageReuse];
        if (cell == nil) {
            cell = [[[ImageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:imageReuse] autorelease];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        ImageTableViewModel *imageModel = self.imageArr[indexPath.row];
        [cell.upImageView sd_setImageWithURL:[NSURL URLWithString:imageModel.coverImageURL] placeholderImage:[UIImage imageNamed:@"漫图占位图"]];
        cell.downLabel.text = imageModel.PicTitle;
        cell.countLabel.text = imageModel.imageCount;
        cell.likeLabel.text = imageModel.likeCount;
        return cell;
    }
    
}

#pragma mark -
#pragma mark tableView跳转方法
#pragma mark -
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([DownloadSingleton shareDownloadSingleton].leftState == collectAnimes) {
        DetailsInfoModel *model = self.animeArr[indexPath.row];
        homeAnimeViewController *homeAnimeVC = [[homeAnimeViewController alloc] init];
        homeAnimeVC.Id = model.infoId;
        homeAnimeVC.tuTitle = model.title;
        [self.navigationController pushViewController:homeAnimeVC animated:YES];
        [homeAnimeVC release];
    } else if ([DownloadSingleton shareDownloadSingleton].leftState == collectNews) {
        NewsTableViewModel *model = self.newsArr[indexPath.row];
        homeNewsViewController *homeNewsVC = [[homeNewsViewController alloc] init];
        homeNewsVC.newsID = model.Id;
        homeNewsVC.newsModel = self.newsArr[indexPath.row];
        [self.navigationController pushViewController:homeNewsVC animated:YES];
        [homeNewsVC release];
    } else {
        ImageTableViewModel *model = self.imageArr[indexPath.row];
        homeImageViewController *homeImageVC = [[homeImageViewController alloc] init];
        homeImageVC.Id = model.Id;
        homeImageVC.modeltitle = model.PicTitle;
        [self.navigationController pushViewController:homeImageVC animated:YES];
        [homeImageVC release];
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat rowHeight = 0;
    switch ([DownloadSingleton shareDownloadSingleton].leftState) {
        case collectAnimes:
            rowHeight = (HEIGHT - 64) / 4;
            break;
        case collectNews:
            rowHeight = (HEIGHT - 64) / 5;
            break;
        case collectImages:
            rowHeight = (HEIGHT - 113) / 3;
            break;
    }
    
    return rowHeight;
}

#pragma mark UISegmentedControl点击方法
- (void)segClick:(UISegmentedControl *)seg {
    switch (seg.selectedSegmentIndex) {
        case 0:
            self.titleLabel.text = @"漫画收藏";
            [self.leftTableView setContentOffset:CGPointMake(0, 0)];
            [self.leftScrollView setContentOffset:CGPointMake(WIDTH * 2 / 3, 0) animated:YES];
            [DownloadSingleton shareDownloadSingleton].leftState = collectAnimes;
            [self.leftTableView reloadData];
            break;
        case 1:
            self.titleLabel.text = @"漫资讯收藏";
            [self.leftTableView setContentOffset:CGPointMake(0, 0)];
            [self.leftScrollView setContentOffset:CGPointMake(WIDTH * 1 / 3, 0) animated:YES];
            [DownloadSingleton shareDownloadSingleton].leftState = collectNews;
            [self.leftTableView reloadData];
            break;
        case 2:
            self.titleLabel.text = @"漫图收藏";
            [self.leftTableView setContentOffset:CGPointMake(0, 0)];
            [self.leftScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
            [DownloadSingleton shareDownloadSingleton].leftState = collectImages;
            [self.leftTableView reloadData];
            break;
    }
}


#pragma mark 返回按钮方法
- (void)backButtonClick:(UIButton *)button {
    
    self.tabBarController.tabBar.hidden = NO;
    
    [self.navigationController popToRootViewControllerAnimated:YES];
    
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppDelegate.LeftSlideVC openLeftView];//打开左侧抽屉
}

#pragma mark 分类按钮方法
- (void)fenleiClick:(UIButton *)button {
    if (self.rightButtonState == isOff) {
        CGPoint oldLeftPoint = self.leftSeg.center;
        CGPoint oldLeftScrollPoint = self.leftScrollView.center;
        self.rightButtonState = isChanging;
        [UIView animateWithDuration:0.15 animations:^{
            self.backView.frame = CGRectMake(0, 0, WIDTH * 2, 50);
            
            self.leftScrollView.center = CGPointMake(oldLeftScrollPoint.x, self.backView.center.y);
            self.leftSeg.center = CGPointMake(oldLeftPoint.x, self.backView.center.y);
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.1 animations:^{
                self.backView.frame = CGRectMake(0, 0, WIDTH * 2, 40);
                
                self.leftScrollView.center = oldLeftScrollPoint;
                self.leftSeg.center = oldLeftPoint;
            } completion:^(BOOL finished) {
                self.rightButtonState = isOn;
            }];
        }];
    } else if (self.rightButtonState == isOn) {
        self.rightButtonState = isChanging;
        [UIView animateWithDuration:0.3 animations:^{
            self.backView.frame = CGRectMake(0, 0, WIDTH * 2, 0);
        } completion:^(BOOL finished) {
            self.rightButtonState = isOff;
        }];
    }
}

#pragma mark 删除功能
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([DownloadSingleton shareDownloadSingleton].leftState == collectAnimes) {
        NSArray *animeSandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *animeSandBoxPath = animeSandBox[0];
        NSString *collctAnimePath = [animeSandBoxPath stringByAppendingPathComponent:@"anime.plist"];
        self.animeArr = [NSKeyedUnarchiver unarchiveObjectWithFile:collctAnimePath];
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            [self.animeArr removeObjectAtIndex:indexPath.row];
            [self.leftTableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationRight];
        }
        // 归档
        [NSKeyedArchiver archiveRootObject:self.animeArr toFile:collctAnimePath];
        
        
    } else if ([DownloadSingleton shareDownloadSingleton].leftState == collectNews) {
        NSArray *newsSandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *newsSandBoxPath = newsSandBox[0];
        NSString *collctNewsPath = [newsSandBoxPath stringByAppendingPathComponent:@"news.plist"];
        self.newsArr = [NSKeyedUnarchiver unarchiveObjectWithFile:collctNewsPath];
        if (editingStyle == UITableViewCellEditingStyleDelete) {
                [self.newsArr removeObjectAtIndex:indexPath.row];
                [self.leftTableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationRight];
            }
            // 归档
            [NSKeyedArchiver archiveRootObject:self.newsArr toFile:collctNewsPath];
    } else {
        NSArray *imageSandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *imageSandBoxPath = imageSandBox[0];
        NSString *collectImagePath = [imageSandBoxPath stringByAppendingPathComponent:@"image.plist"];
        self.imageArr = [NSKeyedUnarchiver unarchiveObjectWithFile:collectImagePath];
        if (editingStyle == UITableViewCellEditingStyleDelete) {
                [self.imageArr removeObjectAtIndex:indexPath.row];
                [self.leftTableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationRight];
            }
            // 归档
            [NSKeyedArchiver archiveRootObject:self.imageArr toFile:collectImagePath];
    }
    
    [DownloadSingleton shareDownloadSingleton].collcetCount = [DownloadSingleton shareDownloadSingleton].collcetCount - 1;
    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *sandBoxPath = sandBox[0];
    NSString *collcetCountBoxPath = [sandBoxPath stringByAppendingPathComponent:@"collcetCount.txt"];
    NSString *str = [NSString stringWithFormat:@"%d",[DownloadSingleton shareDownloadSingleton].collcetCount];
    [str writeToFile:collcetCountBoxPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    NSIndexPath *leftIndexPath = [DownloadSingleton shareDownloadSingleton].leftIndexPath;
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    LeftCollectionViewCell *cell = (LeftCollectionViewCell*)[tempAppDelegate.homeVC.collectionView cellForItemAtIndexPath:leftIndexPath];
    [cell.tableView reloadData];
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
